package vfs.common.tty;

import vfs.common.Regex;
import vfs.common.command.Command;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Holds user input processing cycle
 * <p/>
 * User: serge
 * Date: 17.11.13
 * Time: 23:14
 */
class TtyThread extends Thread
{
    private boolean running;
    private BufferedReader isr;

    TtyThread()
    {
        running = true;
    }

    public void run()
    {
        isr = new BufferedReader(new InputStreamReader(System.in));

        while (running)
        {
            try
            {
                if (isr.ready())
                {
                    String call = isr.readLine();

                /* no input to console - thread is stopping, break cycle */
                    if (call == null)
                    {
                        break;
                    }

                /* if string is empty or contain spaces symbols only */
                    if (Regex.stringMatchesMask(call, "\\s*", false))
                    {
                        Tty.printInvitation();
                        continue;
                    }

                    if (Tty.commandFactory != null)
                    {
                        Command command = Tty.commandFactory.getCommand(call);
                        command.execute();
                    }
                }
                else
                {
                    Thread.sleep(10);
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    }

    void finish()
    {
        running = false;
    }
}
